import 'package:common_utils/common_utils.dart';
import 'package:flutter/services.dart';

///价格输入框和数量输入框的限制
class PrecisionLimitFormatter extends TextInputFormatter {
  int _scale;
  int maximum; //限制最大值

  PrecisionLimitFormatter(this._scale, {this.maximum =10000000000000 });

  RegExp exp = new RegExp("[0-9.]");
  static const String POINTER = ".";
  static const String DOUBLE_ZERO = "00";

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    ///输入完全删除
    if (newValue.text.isEmpty) {
      return TextEditingValue();
    }
    if (newValue.text.startsWith('-') || newValue.text.startsWith('+')) {
      return oldValue;
    }
    double? number = double.tryParse(newValue.text);

    ///只允许输入小数
    if (number == null) {
      return oldValue;
    }
    if (newValue.text.length > oldValue.text.length) {
      if (maximum != null && strToDouble(newValue.text) >= maximum) {
        return oldValue;
      }
      String newText = newValue.text.substring(oldValue.text.length, newValue.text.length);

      ///只允许输入小数
      if (!exp.hasMatch(newText)) {
        return oldValue;
      }
    }

    ///包含小数点的情况
    if (newValue.text.contains(POINTER)) {
      ///包含多个小数
      if (newValue.text.indexOf(POINTER) != newValue.text.lastIndexOf(POINTER)) {
        return oldValue;
      }
      String input = newValue.text;
      int index = input.indexOf(POINTER);

      ///小数点后位数
      int lengthAfterPointer = input.substring(index, input.length).length - 1;

      ///小数位大于精度
      if (lengthAfterPointer > _scale) {
        return oldValue;
      }
    } else if (newValue.text.startsWith(POINTER) || newValue.text.startsWith(DOUBLE_ZERO)) {
      ///不包含小数点,不能以“00”开头
      return oldValue;
    }
    return newValue;
  }

  double strToDouble(String str, [double defaultValue = 0.00]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }
}
